package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Permission;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.http.HttpSession;
import java.util.List;

//提取存储session的JSONID：常量易错
public abstract class UserContext {
    //将两个常量JSONID放到变量中，用方法去返回值，方便使用不易错。
    public static final String EMPLOYEE_IN_SESSION = "EMPLOYEE_IN_SESSION";
    public static final String PERMISSION_IN_SESSION = "PERMISSION_IN_SESSION";

    /**
     * 获得session在类中自己用，外面要用需要该修饰符
     *
     * @return
     */
    private final static HttpSession getSession() {
        //Spring中提供了一个类来让我们获得请求的属性：需要强转
        //ServletRequestAttributes类中：public final HttpServletRequest getRequest() {return this.request;}
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes.getRequest().getSession();
    }

    /**
     * 从session中获取当前登录用户
     *
     * @return
     */
    public final static Employee getCurrentUser() {
        //获得session,在获得session中的User
        Employee employee = (Employee) getSession().getAttribute(EMPLOYEE_IN_SESSION);
        return employee;
    }

    /**
     * 把用户存到session中
     *
     * @param employee
     */
    public final static void setCurrentUser(Employee employee) {
        getSession().setAttribute(EMPLOYEE_IN_SESSION, employee);
    }

    /**
     * 从session中获取当前登录用户的权限
     *
     * @return
     */
    public final static List<String> getPermissions() {
        return (List<String>) getSession().getAttribute(PERMISSION_IN_SESSION);
    }

    /**
     * 把权限存到session中
     *
     * @param permissions
     */
    public final static void setPermissions(List<String> permissions) {
        getSession().setAttribute(PERMISSION_IN_SESSION, permissions);
    }
}
